import axios from 'axios'
import qs from 'qs'
import router from '../router/index.js'

var index_url="http://localhost:8085/"

  // axios 配置
axios.defaults.timeout = 50000;
//根目录
axios.defaults.baseURL = '';
//设置默认请求头
axios.defaults.headers = {
    'X-Requested-With': 'XMLHttpRequest'
}


  // http request 拦截器
axios.interceptors.request.use(
config => {
    if (localStorage.token) {
      config.params  = config.params||{}
      config.params.token = `${localStorage.token}`;
    }
    return config;
},
err => {
    return Promise.reject(err);
});

axios.interceptors.response.use(
	  response => {
	  	
	  	if(response.data.code==401){
	  		 router.replace({
             path: 'login',
             query: {redirect: router.currentRoute.fullPath}
          
           })
	  	}else if(response.data.code==402){
	  		 router.replace({
             path: 'factoryList',
             query: {redirect: router.currentRoute.fullPath}
          
           })
	  	}  	
//  switch () {
//    case 401:
//      // 401 清除token信息并跳转到登录页面
//         router.replace({
//           path: 'login2',
//           query: {redirect: router.currentRoute.fullPath}
//        
//         })
//    case 402:
//       	  		 router.replace({
//           path: 'factoryList',
//           query: {redirect: router.currentRoute.fullPath}
//        
//         })   
//         	
//
//  }
    return response;
},
error => {
    throw error
});

export default {
	//get请求
    get (url,param) {

      return new Promise((resolve,reject) => {
				url=index_url+url
        axios({
          method: 'get',
					url,
					xhrFields: {
						withCredentials: true
					},
					crossDomain: true,
          params: param
        }).then(res => {
          resolve(res)
        }).catch(err =>{
					reject(err)
				})
      })
    },
  //post请求
    post (url,param) {
      return new Promise((resolve,reject) => {
						url=index_url+url
        axios({
				method: 'post',
    					url,
      xhrFields: {
        withCredentials: true
      },
      crossDomain: true,
      data: param,
      traditional: true,
      timeout: 30000,

        }).then(res => {
          resolve(res)
        }).catch(err =>{
					reject(err)
				})
      })
     }
  }